package com.example.aijiancece.database;

import android.content.Context;

import com.example.aijiancece.database.entity.HistoryEntity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class DatabaseHelper {
    private static DatabaseHelper instance;
    private final AppDatabase database;
    private final SimpleDateFormat dateFormat;

    private DatabaseHelper(Context context) {
        database = AppDatabase.getInstance(context);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseHelper(context.getApplicationContext());
        }
        return instance;
    }

    public void addHistory(String content, String result, String analysis) {
        new Thread(() -> {
            HistoryEntity entity = new HistoryEntity(
                    content,
                    result,
                    analysis,
                    System.currentTimeMillis()
            );
            database.historyDao().insert(entity);
        }).start();
    }

    public List<HistoryEntity> getAllHistory() {
        return database.historyDao().getAll();
    }

    public String formatTime(long timestamp) {
        return dateFormat.format(new Date(timestamp));
    }

    public void deleteHistory(String id) {
        new Thread(() -> {
            database.historyDao().delete(id);
        }).start();
    }

    public void clearHistory() {
        new Thread(() -> {
            database.historyDao().deleteAll();
        }).start();
    }
} 